﻿using System;
using System.Collections.Generic;

namespace IFramework
{
    public class ObserveManager : Singleton<ObserveManager>,IObserveManager
    {
        private Dictionary<Type,Observe> observes;
        public override void OnSingletonInit()
        {
            observes = new Dictionary<Type, Observe>();
        }
        public override void Dispose()
        {
            base.Dispose();
            var temp = observes.Values.GetEnumerator();
            while (temp.MoveNext())
            {
                temp.Current.Dispose();
            }
            temp.Dispose();
            observes.Clear();
            observes = null;
        }

        public void Notify<T>(EventArgs args, int code, params object[] message) 
        {
            if (!observes.ContainsKey(typeof(T))) return;
            observes[typeof(T)].Notify(args,code,message);
        }
        public void Notify<T>(EventArgs args,T t, int code, params object[] message) 
        {
            if (!observes.ContainsKey(t.GetType())) return;
            observes[t.GetType()].Notify(args, code, message);
        }
        public void DelayNotify<T>(EventArgs args, int code, params object[] message) 
        {
            Loom.Instance.RunOnMainThread(()=>Notify<T>(args, code, message));
        }
        public void DelayNotify<T>(EventArgs args, T t, int code, params object[] message) 
        {
            Loom.Instance.RunOnMainThread(() => Notify<T>(args,t, code, message));
        }
        public void AddObserver<T>(IObserver observer)
        {
            if (!observes.ContainsKey(typeof(T)))
            {
                observes.Add(typeof(T), new Observe(typeof(T)));
            }
            observes[typeof(T)].AddObserver(observer);
        }
        public void AddObserver<T>(T t, IObserver observer)
        {
            if (!observes.ContainsKey(t.GetType()))
            {
                observes.Add(t.GetType(), new Observe(t.GetType()));
            }
            observes[t.GetType()].AddObserver(observer);
        }
        public void RemoveObserver<T>(IObserver observer)
        {
            if (!observes.ContainsKey(typeof(T))) return;
            observes[typeof(T)].RemoveObserver(observer);
        }
        public void RemoveObserver<T>(T t, IObserver observer)
        {
            if (!observes.ContainsKey(t.GetType())) return;
            observes[t.GetType()].RemoveObserver(observer);
        }
    }
}